package com.huahua.api.scheduled;

import com.huahua.api.repository.CloudPrintDeviceRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import reactor.core.scheduler.Schedulers;

import java.time.LocalDateTime;

/**
 * @author Huahua-Ai
 * @date 2025-07-24 18:00:00
 * @description 设备心跳检查定时任务
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class DeviceHeartbeatChecker {

    private final CloudPrintDeviceRepository deviceRepository;

    /**
     * 每30秒检查一次设备心跳
     * 超过60秒没有心跳的设备标记为离线
     */
    @Scheduled(fixedDelay = 30000)
    public void checkDeviceHeartbeat() {
        LocalDateTime timeout = LocalDateTime.now().minusSeconds(60);

        deviceRepository.findByStatusAndLastHeartbeatBefore("online", timeout)
                .flatMap(device -> {
                    device.setStatus("offline");
                    return deviceRepository.save(device);
                })
                .subscribeOn(Schedulers.boundedElastic())
                .subscribe(
                        device -> log.info("设备心跳超时，标记为离线: {}", device.getDeviceId()),
                        error -> log.error("检查设备心跳失败", error)
                );
    }
}
